<template>
  <div class="addgood">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info" show-icon center> </el-alert>
      <!-- active接收数字类型 -->
      <el-steps
        :space="200"
        :active="parseInt(activeIndex)"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        ref="addRef"
        :model="addForm"
        :rules="addFormRules"
        label-position="top"
      >
        <!--  v-model接收字符串 -->
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="tapsleave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="props"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in goodparams"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="val"
                  v-for="(val, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in goodattr"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"> </el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action表示上传后台的API 
            on-preview预览事件
            list-type预览组件的呈现方式
            upload有自己默认的axios请求方式 -->
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!--     富文本编辑器使用 -->
            <quill-editor v-model="addForm.goods_introduce" ref="myQuillEditor">
            </quill-editor>
            <el-button type="primary" class="addbtn" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!--  预览图片对话框 -->
      <el-dialog title="图片预览" :visible.sync="prewdialog" width="50%">
        <img :src="prewPath" mode="" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
//导入富文本编辑器
import { quillEditor } from "vue-quill-editor";
//导入富文本编辑器的对应样式

import _ from "lodash";

export default {
  name: "",
  components: {
    quillEditor,
  },
  data() {
    return {
      activeIndex: "0",
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        //存放图片的临时文件
        pics: [],
        //商品内容
        goods_introduce: "",
        attrs: [],
      },
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择正确的商品", trigger: "change" },
        ],
      },
      cateList: [],
      //商品参数数据
      goodparams: [],
      //商品属性
      goodattr: [],
      props: { expandTrigger: "hover", label: "cat_name", value: "cat_id" },
      //upload组件的请求头
      headerObj: {
        Authorization: sessionStorage.getItem("token"),
      },
      //图片预览对话框的显示
      prewdialog: false,
      prewPath: "",
    };
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$request({
        url: "categories",
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.cateList = res.data;
      // console.log(res.data);
    },
    handleChange(valId) {
      //console.log(this.addForm.goods_cat);
      if (this.addForm.goods_cat.length !== 3) {
        return (this.addForm.goods_cat = []);
      }
    },
    tapsleave(newName, oldName) {
      //console.log(newName, oldName);
      if (oldName === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请选择商品分类");
        return false;
      }
    },
    async tabClick() {
      if (this.activeIndex === "1") {
        const { data: res } = await this.$request({
          url: `categories/${this.getCateId}/attributes`,
          params: {
            sel: "many",
          },
        });
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        }
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        });
        this.goodparams = res.data;
        //console.log(res);
      } else if (this.activeIndex === "2") {
        const { data: res } = await this.$request({
          url: `categories/${this.getCateId}/attributes`,
          params: {
            sel: "only",
          },
        });
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        }
        this.goodattr = res.data;
        console.log(res);
      }
    },
    //处理图片预览
    handlePreview(file) {
      console.log(file);
      this.prewPath = file.response.data.url;
      this.prewdialog = true;
    },
    //上传成功
    handleSuccess(response) {
      //response上传成功返回的信息
      //console.log(response);
      const picInfo = { pic: response.data.tmp_path };
      this.addForm.pics.push(picInfo);
      console.log(this.addForm);
    },
    //删除图片
    handleRemove(file) {
      //删除文件的信息
      console.log(file);
      //1.获取将要删除图片的临时路径;
      //从pics数组中，找到图片对应的索引值
      //splice删除
      const filepath = file.response.data.tmp_path;
      const index = this.addForm.pics.findIndex(
        (item) => item.pic === filepath
      );
      this.addForm.pics.splice(index, 1);
      console.log(this.addForm);
    },
    add() {
      //添加预验证
      this.$refs.addRef.validate(async (val) => {
        if (!val) {
          this.$message.error("表单存在空选项，请提交完整的表单");
        }
        //发请求goods_cat  以为','分割的分类列表这个会冲突级联选择器的v-model要求的数组

        //深拷贝插件lodash解决
        let newForm = _.cloneDeep(this.addForm);
        newForm.goods_cat = newForm.goods_cat.join(",");
        //处理动态参数跟静态属性
        this.goodparams.forEach((item) => {
          const paramsInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(","),
          };
          this.addForm.attrs.push(paramsInfo);
        });
        this.goodattr.forEach((item) => {
          const attrInfo = {
            attr_id: item.attr_id,
            //本身就是字符串
            attr_value: item.attr_vals,
          };
          this.addForm.attrs.push(attrInfo);
        });
        newForm.attrs = this.addForm.attrs;
        /*      console.log("动态v参数", this.goodparams, "静态属性", this.goodattr); */

        console.log(newForm);
        //发起提交的请求
        const { data: res } = await this.$request({
          url: "goods",
          method: "post",
          data: newForm,
        });
        console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg);
        }
        this.$message.success("商品创建成功");
        this.$router.push("goods");
      });
    },
  },
  computed: {
    getCateId() {
      if (this.addForm.goods_cat.length !== 3) {
        return;
      }
      return this.addForm.goods_cat[this.addForm.goods_cat.length - 1];
    },
  },
  created() {
    this.getCateList();
  },
};
</script>
<style lang="scss" scoped>
.el-steps {
  margin: 20px 0;
}

.el-step__main {
  text-align: center;
}
.el-checkbox {
  margin: 5px !important;
}
.el-dialog {
  img {
    width: 100%;
  }
}
.addbtn {
  margin-top: 30px;
}
</style>
